<!-- src/views/live/index.vue -->
<template>
    <div class="live-room">
        <div class="video-container">
            <!-- 视频播放器 -->
            <div v-if="loading" class="loading-container">
                <div class="loading-spinner"></div>
                <p>加载中...</p>
            </div>
            <CustomVideoPlayer v-else :sources="videoSources" :chatMessages="chatMessages"
                @sendMessage="handleSendMessage" :qualities="videoQualities" @toggleDanmu="handleToggleDanmu"
                class="video-player" />
            <!-- 弹幕 -->
            <div class="danmaku-container" v-if="isDanmuVisible" ref="liveDanmuContainer">
                <ul class="danmaku-messages">
                    <li v-for="message in  danmakuMessages" :key="message.id" class="danmaku-message"
                        :style="getDanmakuStyle(message)" :data-id="message.id"
                        @mouseenter="handleMouseEnter(message.id)" @mouseleave="handleMouseLeave(message.id)">
                        <span class="danmaku-user">{{ message.user }}:</span>
                        <span class="danmaku-text" :style="{ color: message.color }">{{ message.text }}</span>
                        <i :class="['iconfont', message.isLiked ? 'icon-dianzan1' : 'icon-dianzan']"
                            @click="likeMessage(message.id)" v-show="message.isHovered">
                        </i>
                    </li>
                </ul>
            </div>
        </div>
        <div class="chat-container">
            <!-- 聊天窗口 -->
            <ul class="chat-messages">
                <li v-for="(message, index) in chatMessages" :key="index" class="chat-message"
                    :style="{ animationDelay: index * 0.5 + 's' }">
                    <span class="chat-user">{{ message.user }}:</span>
                    <span class="chat-text">{{ message.text }}</span>
                </li>
            </ul>
            <div class="chat-input">
                <input type="text" v-model="newMessage" placeholder="输入消息" @keyup.enter="sendMessage" />
                <button @click="sendMessage">发送</button>
            </div>
        </div>
        <Notification></Notification>
    </div>
</template>

<script setup>
import { useDanmuStore } from '../../stores/danmu/danmu'
import { ElMessage } from 'element-plus';
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from 'vue';
const videoQualities = [
    { label: '原画', src: 'https://cn-jsyz-ct-03-31.bilivideo.com/live-bvc/952695/live_773977_8790152_bluray/index.m3u8?expires=1735572093&len=0&oi=993562372&pt=web&qn=10000&trid=100718e6762df2006fef64178d461a67772ac&sigparams=cdn,expires,len,oi,pt,qn,trid&cdn=cn-gotcha01&sign=14dfdcef810a11576963e985aaa6507b&site=4618b9ffd4a24657b314794ea1642f2e&free_type=0&mid=434049513&sche=ban&bvchls=1&sid=cn-jsyz-ct-03-31&chash=1&bmt=1&sg=lr&trace=25&isp=ct&rg=East&pv=Fujian&hot_cdn=57417&source=puv3_onetier&flvsk=1304f646dfeb4df8b6e7ff33c167d3ad87b2a035213a12b2efcdf778dee61a04&deploy_env=prod&suffix=bluray&origin_bitrate=1021182&sl=3&p2p_type=1&qp=hv_10000&sk=657866af8fc16d8b2b84dfdde3e98143e94acb5d1a3a50bd0d253c50ef412f31&pp=rtmp&score=1&info_source=cache&vd=nc&zoneid_l=151371777&sid_l=stream_name_cold&src=puv3&order=1' },
    { label: '高清', src: 'https://cn-jsyz-ct-03-73.bilivideo.com/live-bvc/352366/live_773977_8790152_2500/index.m3u8?expires=1735575321&len=0&oi=993562372&pt=web&qn=250&trid=100716dbd4b07deb0eab3cfd029ed06772b9&sigparams=cdn,expires,len,oi,pt,qn,trid&cdn=cn-gotcha01&sign=1e70899d4be4e36d06a221078dd121b3&site=d81f5e85ae719a4460aadcfc88b4b223&free_type=0&mid=434049513&sche=ban&bvchls=1&sid=cn-jsyz-ct-03-73&chash=1&bmt=1&sg=lr&trace=25&isp=ct&rg=East&pv=Fujian&sk=657866af8fc16d8b2b84dfdde3e98143e94acb5d1a3a50bd0d253c50ef412f31&info_source=cache&score=1&hot_cdn=57417&pp=rtmp&p2p_type=1&origin_bitrate=1020718&sl=3&source=puv3_onetier&flvsk=1304f646dfeb4df8b6e7ff33c167d3ad87b2a035213a12b2efcdf778dee61a04&deploy_env=prod&suffix=2500&vd=nc&zoneid_l=151371777&sid_l=stream_name_cold&src=puv3&order=1' }
];
const loading = ref(true); // 加载状态
const danmuStore = useDanmuStore();
//定义是否点赞的状态
const isHovering = ref(false);
//设置id,用于获取弹幕
let messageIdCounter = ref(9);
//用于存储已经发送的弹幕
const displayedDanmakus = new Set();
// 弹幕消息
const danmakuMessages = ref([]);
// { user: '弹幕1', text: '欢迎来到直播间！' },
const chatMessages = ref([
    { user: '用户1', text: '欢迎来到直播间！' },
    { user: '用户2', text: '主播好！' },
    { user: '用户3', text: '今天直播什么？' },
    { user: '用户4', text: '我想看看你们的项目' },
    { user: '用户5', text: '好的，我马上开通直播权限' },
    { user: '用户6', text: '好的，祝你们玩得开心！' },
    { user: '用户7', text: '你好，请问有什么可以帮助你吗？' },
    { user: '用户8', text: '今天天气不错，祝你们心情愉快！' }
]);
const hoveredIndex = ref(null);
const newMessage = ref('');
const usedTopValues = new Set(); // 记录已经使用的弹幕top值
const trackCount = ref(8) // 弹幕条数
const tracks = ref(Array.from({ length: trackCount.value }, () => []))// 弹幕轨道
const trackTops = ref(Array.from({ length: trackCount.value }, (_, i) => `${(i * 100) / trackCount + 5}%`))// 弹幕轨道top值
const videoSources = [
    { label: '原画', src: 'https://cn-jsyz-ct-03-31.bilivideo.com/live-bvc/952695/live_773977_8790152_bluray/index.m3u8?expires=1735572093&len=0&oi=993562372&pt=web&qn=10000&trid=100718e6762df2006fef64178d461a67772ac&sigparams=cdn,expires,len,oi,pt,qn,trid&cdn=cn-gotcha01&sign=14dfdcef810a11576963e985aaa6507b&site=4618b9ffd4a24657b314794ea1642f2e&free_type=0&mid=434049513&sche=ban&bvchls=1&sid=cn-jsyz-ct-03-31&chash=1&bmt=1&sg=lr&trace=25&isp=ct&rg=East&pv=Fujian&hot_cdn=57417&source=puv3_onetier&flvsk=1304f646dfeb4df8b6e7ff33c167d3ad87b2a035213a12b2efcdf778dee61a04&deploy_env=prod&suffix=bluray&origin_bitrate=1021182&sl=3&p2p_type=1&qp=hv_10000&sk=657866af8fc16d8b2b84dfdde3e98143e94acb5d1a3a50bd0d253c50ef412f31&pp=rtmp&score=1&info_source=cache&vd=nc&zoneid_l=151371777&sid_l=stream_name_cold&src=puv3&order=1' },
    { label: '高清', src: 'https://cn-jsyz-ct-03-73.bilivideo.com/live-bvc/212595/live_773977_8790152_2500/index.m3u8?expires=1735574376&len=0&oi=993562372&pt=web&qn=250&trid=100740d9fa8fb8389baf4ad5550fef6772b5&sigparams=cdn,expires,len,oi,pt,qn,trid&cdn=cn-gotcha01&sign=6e5ecbcd7f73d22d153ba5a834bede18&site=99e73c3dd5b1eea9f5e5b9976b1ec174&free_type=0&mid=434049513&sche=ban&bvchls=1&sid=cn-jsyz-ct-03-73&chash=1&bmt=1&sg=lr&trace=8388633&isp=ct&rg=East&pv=Fujian&origin_bitrate=1022488&p2p_type=1&hot_cdn=57417&pp=rtmp&sk=657866af8fc16d8b2b84dfdde3e98143e94acb5d1a3a50bd0d253c50ef412f31&deploy_env=prod&suffix=2500&source=puv3_onetier&score=1&sl=3&flvsk=1304f646dfeb4df8b6e7ff33c167d3ad87b2a035213a12b2efcdf778dee61a04&info_source=cache&vd=nc&zoneid_l=151371777&sid_l=stream_name_cold&src=puv3&order=1' }
];
const colors = ref([
    '#27ba9b', '#ff7f50', '#32cd32', '#ffa500', '#4682b4', '#ff69b4'
])
//定义点赞弹幕的数组
const likedDanmakus = ref(JSON.parse(localStorage.getItem('likedDanmakus')) || []);
const isDanmuVisible = ref(danmuStore.isDanmuVisible);
//引用弹幕ref
const liveDanmuContainer = ref(null);
//处理子组件handleToggleDanmu事件
const handleToggleDanmu = (visible) => {
    isDanmuVisible.value = visible;
    if (!visible) {
        console.log('正在清理中...');
        clearInterval(timer);// 确保清除旧的计时器
        clearAllDanmakus();
    } else {
        console.log('弹幕显示中...');
        // 延迟一段时间再重新启用弹幕
        setTimeout(() => {
            timer = setInterval(() => {
                addChatMessage();
            }, getRandomInterval())
        }, 2000)
    }
}
// 清除所有弹幕的函数
const clearAllDanmakus = () => {
    if (!liveDanmuContainer.value) {
        console.log('弹幕容器未初始化');
        return;
    }
    // 使用 ref 直接操作 DOM 元素
    const container = liveDanmuContainer.value;
    try {
        danmakuMessages.value = [];
        // 清空轨道数组和已显示的弹幕集合
        tracks.value = Array.from({ length: trackCount.value }, () => []);
        displayedDanmakus.clear();
    } catch (error) {
        console.error(error);
    }
};
//随机弹幕颜色
const getRandomColor = () => {
    // 90%的概率返回白色
    if (Math.random() < 0.8) {
        return '#fff'
    }
    // 10%的概率返回数组中的随机颜色
    return colors.value[Math.floor(Math.random() * colors.value.length)]
}
//定义点赞逻辑
const likeMessage = (index) => {
    const messageIndex = danmakuMessages.value.findIndex(msg => msg.id === index);
    if (messageIndex !== -1) {
        console.log('点赞了', index);
        //点赞状态切换
        danmakuMessages.value[messageIndex].isLiked = !danmakuMessages.value[messageIndex].isLiked;

        //点赞以后加入数组中
        if (danmakuMessages.value[messageIndex].isLiked) {
            likedDanmakus.value.push(danmakuMessages.value[messageIndex]);
        } else {
            //取消点赞时，从数组中移除 
            likedDanmakus.value = likedDanmakus.value.filter(item => item.id !== messageIndex);
        }
    }
    //将index存储到本地存储中,用于记录点赞过的弹幕
    localStorage.setItem('likedDanmakus', JSON.stringify(likedDanmakus.value));
}
const handleMouseEnter = (id) => {
    const messageIndex = danmakuMessages.value.findIndex(msg => msg.id === id);
    if (messageIndex !== -1) {
        danmakuMessages.value[messageIndex].isHovered = true;
    }
}
const handleMouseLeave = (id) => {
    const messageIndex = danmakuMessages.value.findIndex(msg => msg.id === id);
    if (messageIndex !== -1) {
        danmakuMessages.value[messageIndex].isHovered = false;
    }
}
//添加弹幕
const addDanmaku = (message) => {
    let trackIndex = -1;
    let minTrackLength = Infinity;

    // 优先选择空轨道
    const availableTrackIndex = tracks.value.findIndex(track => track.length === 0);
    if (availableTrackIndex !== -1 && Math.random() > 0.2) {
        // 20% 的概率选择其他轨道
        trackIndex = availableTrackIndex;
    } else {
        //如果没有空轨道，选择最近最少使用的轨道
        for (let i = 0; i < trackCount.value; i++) {
            if (tracks.value[i].length < minTrackLength) {
                minTrackLength = tracks.value[i].length
                trackIndex = i;
            }
        }
        // 有一定的概率选择随机轨道
        if (trackIndex === -1 ||Math.random() > 0.5) {
            // 50% 的概率选择随机轨道
            trackIndex = Math.floor(Math.random() * trackCount.value);
        }
        //加入随机轨道
        // trackIndex = Math.floor(Math.random() * trackCount.value)
    }
    // 如果没有找到合适的轨道，选择随机轨道
    if (trackIndex === -1) {
        trackIndex = Math.floor(Math.random() * trackCount.value);
    }
    // 加入轨道
    if (trackIndex >= 0 && trackIndex < tracks.value.length) {
        //正确添加二维数组
        tracks.value[trackIndex] = tracks.value[trackIndex] || [];
        tracks.value[trackIndex].push(message);
        danmakuMessages.value.push(message);
        // 更新 trackTops
        trackTops.value = Array.from({ length: trackCount.value }, (_, i) => `${(i * 100) / trackCount.value + 5}%`);
    }
    // console.log(`弹幕 ${message.id} 加入轨道 ${trackIndex}`); // 添加日志
}
//移除弹幕
const removeDanmaku = (message, trackIndex) => {
        const index = danmakuMessages.value.findIndex(item => item.id === message.id);
        if (index !== -1) {
            danmakuMessages.value.splice(index, 1);
        }
        if (trackIndex >= 0 && trackIndex < tracks.value.length) {
            const track = tracks.value[trackIndex];
            const trackMessageIndex = track.findIndex(item => item.id === message.id);
            if (trackMessageIndex !== -1) {
                track.splice(trackMessageIndex, 1);
            }
        }
};
// 弹幕样式
const getDanmakuStyle = (message) => {
    const trackIndex = tracks.value.findIndex(track => track.some(item => item.id === message.id));
    if (trackIndex !== -1) {
        if (trackIndex < 0 || trackIndex >= trackCount.value) {
            console.error(`trackIndex ${trackIndex} 超出范围`); // 添加这行
        }
        return {
            top: trackTops.value[trackIndex],
            animationDelay: `${(trackIndex * 0.5)}s`,
        };
    }
    return {};
};
const handleSendMessage = (message) => {
    const newMsg = { id: messageIdCounter.value++, user: '我', text: message };
    chatMessages.value.push(newMsg);
    addDanmaku(newMsg);
    newMessage.value = '';
    scrollToBottom();
};
const sendMessage = () => {
    if (newMessage.value.trim() === '') return;
    const messageText = newMessage.value;
    const newMsg = { id: messageIdCounter.value++, user: '我', text: messageText };
    chatMessages.value.push(newMsg);
    // 发送弹幕
    addDanmaku(newMsg);
    //确保新弹幕的添加不会影响现有弹幕的位置。
    nextTick(() => {
        const el = document.querySelector(`.danmaku-message[data-id="${newMsg.id}"]`)
        if (el) {
            // 监听动画结束事件
            el.addEventListener('animationend', () => {
                removeDanmaku(newMsg);
            })
        }
    })
    newMessage.value = '';
    scrollToBottom();
};

const scrollToBottom = () => {
    const chatMessagesElement = document.querySelector('.chat-messages');
    if (chatMessagesElement) {
        chatMessagesElement.scrollTop = chatMessagesElement.scrollHeight;
    }
};

// 定义定时器
let timer;

// 定义延时发送弹幕函数
const addChatMessage = () => {
    const newMessages = [
        { user: '用户9', text: '我也来了！' },
        { user: '用户10', text: '你们好，一起加油！' },
        { user: '用户11', text: '非常喜欢你们的直播内容！' },
        { user: '用户12', text: '你们辛苦了，谢谢主播！' },
        { user: '用户13', text: '主播，你好！' },
        { user: '用户14', text: '你好，请问有什么可以帮助你吗？' },
        { user: '用户15', text: '今天天气不错，祝你们心情愉快！' },
        { user: '用户16', text: '你好，请问有什么可以帮助你吗？' },
    ];
    // 随机用户昵称池
    const userPool = [
        'chen',
        'liu',
        'wang',
        'zhao',
        'sun',
        'li',
        'zhou',
        'wu',
        'peng',
        'zheng',
        'liang',
        'fu',
        'huang',
        'peng',
        'lou',
        'guo',
        'wa',
        'xia',
        'fu',
        'xie',
        'zhong',
        'zhu',
    ];
    // 随机消息内容池
    const messagePool = [
        '主播小兔你今天好漂亮！',
        '这个功能真是太棒了！',
        '我也想要这个功能！',
        '你们团队真的太厉害了！',
        '今天直播内容好有趣！',
        '支持主播小兔！',
        '加油加油！',
        '期待下次直播！',
        '这个项目真是太酷了！',
        '你们辛苦了！',
        '学到了很多新知识！',
        '主播小兔讲得真好！',
        '这个设计太赞了！',
        '我也要试试！',
        '感谢分享！',
        '太棒了！',
        '主播小兔你真有才华！',
        '这个直播真不愧是你的风格！',
        '你们的新项目令人期待！',
        '我觉得这个互动环节很好玩！',
        '希望你们的直播时间能更长一些！',
        '主播小兔你真的很会讲故事！',
        '这个画面质量真好，看得清楚！',
        '你们的后台应该是很强大的吧！',
        '感谢你们带来的欢乐！',
        '主播小兔你每次直播都有新惊喜！',
        '我希望你们团队能带来更多这样的直播！',
        '这个话题真是很有意思，我完全被吸引住了！',
        '主播小兔你的声音听起来很舒服！',
        '你们的直播内容总是那么丰富多样！',
        '你好啊',
        '晚上好',
        '这个是你们的直播吗？',
        '是的，我也很喜欢你的直播！',
        '你好，我是你的粉丝',
        '我不怎么会讲话，但是我很喜欢你的直播！',
        '你好，我是你的粉丝，我也很喜欢你的直播！',
        '这是很长很长的弹幕消息，我想换行一下看看效果,这是很长很长很长很长很长很长很长的弹幕消息'
    ];
    let randomUser;
    let randomMessage;
    let messageCombination;
    let attempts = 0;
    const maxAttempts = 1000; // 防止无限循环
    do {
        randomUser = userPool[Math.floor(Math.random() * userPool.length)];
        randomMessage = messagePool[Math.floor(Math.random() * messagePool.length)];
        messageCombination = `${randomUser}:${randomMessage}`;
        attempts++;
        if (attempts > maxAttempts) {
            ElMessage.error("无法生成新的弹幕组合，已超出最大尝试次数");
            return;
        }
    } while (displayedDanmakus.has(messageCombination));
    //定义消息
    const newMsg = { id: messageIdCounter.value++, user: randomUser, text: randomMessage, color: getRandomColor() };
    chatMessages.value.push(newMsg);
    if (!displayedDanmakus.has(messageCombination)) {
        displayedDanmakus.add(messageCombination);
        addDanmaku(newMsg)
        adjustDanmakuAnimation(); // 调整弹幕动画
        // 渲染完成后移除该弹幕
        // 确保新弹幕的添加不会影响现有弹幕的位置
        nextTick(() => {
            const el = document.querySelector(`.danmaku-message[data-id="${newMsg.id}"]`);
            if (el) {
                const containerWidth = el.parentElement.offsetWidth; // 弹幕容器宽度
                const messageWidth = el.scrollWidth; // 弹幕宽度
                const maxWidth = 300; // 最大宽度
                const actualWidth = Math.min(messageWidth, maxWidth); // 实际宽度不超过最大宽度
                const totalWidth = containerWidth + actualWidth; // 总宽度
                const duration = totalWidth / containerWidth * 10; // 动画持续时间

                // el.style.width = `${actualWidth}px`; // 设置实际宽度
                // el.style.animationDuration = `${duration}s`; // 设置动画持续时间
                // el.style.transform = `translateX(100%)`; // 初始位置在屏幕右侧

                // 监听动画结束事件
                el.addEventListener('animationend', () => {
                    removeDanmaku(newMsg);
                });
            }
        });
    }
    scrollToBottom(); // 每次添加新消息时滚动到底部
    // 如果该消息的组合未显示过，就添加到已显示的集合
    displayedDanmakus.add(messageCombination);
    let lastNotificationTime = 0;
    const notificationInterval = 10000; // 10秒
    // 显示全站通知
    const currentTime = Date.now();
    if (currentTime - lastNotificationTime > notificationInterval) {
        danmuStore.showNotification('欢迎:' + randomUser + '加入直播间', '#27ba9b', '#fff');
        lastNotificationTime = currentTime;
    }
};

// 生成随机的时间间隔
const getRandomInterval = () => {
    // 5-15秒之间随机数
    // return Math.floor(Math.random() * 11 + 5) * 1000;
    return 1000; // 2秒发送一次弹幕
};
onMounted(() => {
    // 模拟视频加载过程
    setTimeout(() => {
        loading.value = false; // 加载完成

    }, 1000); // 假设 3 秒后视频加载完成

    // 设置定时器，每隔5秒发送一条新的弹幕
    if (danmuStore.isDanmuVisible) {
        timer = setInterval(() => {
            addChatMessage();
        }, getRandomInterval());
        scrollToBottom();
    }

    //重新渲染top值
    danmakuMessages.value.forEach((message, index) => {
        nextTick(() => {
            const el = danmakuRefs.value[index];
            if (el) {
                // danmakuRefs(el)
            }
        })
    })
});
const showControls = (id) => {
    hoveredIndex.value = id;
};

const hideControls = () => {
    hoveredIndex.value = null;
};
onUnmounted(() => {
    // 清除定时器
    clearInterval(timer);
});
watch(() => trackCount.value, (newTrackCount) => {
    trackTops.value = Array.from({ length: newTrackCount }, (_, i) => `${(i * 100) / newTrackCount + 5}%`);
    console.log("trackTops updated:", trackTops.value);
});
//动态计算弹幕动画
const adjustDanmakuAnimation = () => {
    const danmakuElements = document.querySelectorAll('.danmaku-message');
    danmakuElements.forEach(message => {
        const containerWidth = message.parentElement.offsetWidth;//弹幕容器宽度
        const messageWidth = message.scrollWidth;//弹幕宽度
        const totalWidth = containerWidth + messageWidth;//总宽度
        const duration = totalWidth / containerWidth * 10;//动画持续时间
        message.style.animationDuration = `scrollLeft ${duration}s linear`;//设置动画持续时间
    })
}
</script>

<style scoped lang="scss">
/* video 加载样式*/
.loading-spinner {
    border: 4px solid rgba(255, 255, 255, 0.3);
    border-top: 4px solid #fff;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    animation: spin 1s linear infinite;
    margin-right: 10px;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

.live-room {
    display: flex;
    height: 100vh;
    width: 100vw;
    overflow: hidden;
}

.video-container {
    flex: 3;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
}

.danmaku-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    pointer-events: none;
}

.danmaku-messages {
    list-style: none;
    padding: 0;
    margin: 0;
    max-height: 100%;
    display: flex;
    overflow: hidden;
}

.danmaku-message {
    position: absolute;
    width: 100%;
    left: 100%;
    /* 可以调整为其他值以改变弹幕显示的位置 */
    right: 0;
    animation: scrollLeft 10s linear forwards;
    pointer-events: all;
    white-space: nowrap; // 确保弹幕文本不换行
    z-index: 1;
    /* 确保弹幕消息可以接收 hover 事件 */
    /* 可以根据需要调整持续时间 */
    &:hover {
        animation-play-state: paused;
    }
}

.danmaku-user {
    font-weight: bold;
    margin-right: 5px;
    color: #27ba9b;
    /* 弹幕用户名的颜色 */
}

.danmaku-text {
    color: #fff;
    /* 弹幕文本的颜色 */
}

.like-button {
    background-color: transparent;
    border: none;
    color: white;
    cursor: pointer;
    margin: 0 2px;
    font-size: 10px;
}

@keyframes scrollLeft {
    from {
        transform: translateX(10%);
        /* 开始时稍微向右，以便平滑进入 */
    }

    to {
        transform: translateX(-150%);
        /* 结束时完全移出屏幕 */
    }
}

.chat-container {
    display: flex;
    flex-direction: column;
    padding: 0 10px;
    background-color: rgba(0, 0, 0, 0.7);
    color: #fff;
    justify-content: space-between;
    width: 20%;
}

.chat-messages {
    flex: 1;
    list-style: none;
    padding: 0 10px;
    margin: 0;
    overflow-y: auto;
    height: 30%;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    border-radius: 4px;
}

.chat-message {
    position: relative;
    overflow: hidden;
    white-space: pre-wrap;
    word-wrap: break-word;
    margin-bottom: 5px;
    user-select: text;
}

.chat-user {
    font-weight: bold;
    margin-right: 5px;
    color: #27ba9b
}

.chat-text {
    color: #fff;
    word-wrap: break-word;
    /* 确保消息内容在超出宽度时自动换行 */
    white-space: pre-wrap;
    /* 保留空白符并允许换行 */
}

.chat-input {
    display: flex;
    margin-top: 10px;
}

.chat-input input {
    flex: 1;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px 0 0 4px;
    background-color: #fff;
    color: #333;
}

.chat-input button {
    padding: 8px 12px;
    border: 1px solid #ccc;
    border-radius: 0 4px 4px 0;
    background-color: #f0f0f0;
    cursor: pointer;
    color: #333;
}

.iconfont {
    font-size: 16px;
    color: #27ba9b;
    cursor: pointer;
}
</style>
